const express = require('express');
const router = express.Router();
//导入数据库操作模块
const db = require('../db/index');

//获取setting列表
router.get('/list', (req, res) => {
    db.query(`select * from setting order by id desc`, (err, result) => {
        if (err) {
            console.log(err);
            res.json({
                code: 500,
                message: '服务器错误'
            });
        } else {
            res.json({
                code: 200,
                list: result
            });
        }
    })
});

//新设置
router.post('/insert', (req, res) => {
    const name = req.body.name;
    const logo = req.body.logo;
    const logo_name = req.body.logo_name;
    const status = 0;

    const setting = {
        name,
        logo,
        logo_name,
        status
    }

    //插入评论
    db.query(`insert into setting set ?`, setting, (err, result) => {
        if (err) {
            console.log(err);
            res.json({
                code: 500,
                message: '服务器错误'
            });
        } else {
            res.json({
                code: 200,
                message: '评论成功'
            });
        }
    })
});

//删除
router.post('/delete', (req, res) => {
    const id = req.body.id;
    //删除轮播图
    db.query(`delete from setting where id = ${id}`, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                message: '服务器错误'
            });
        } else {
            res.json({
                code: 200,
                message: '删除成功'
            });
        }
    });
});

//编辑设置
router.post('/edit', (req, res) => {
    const id = req.body.id;
    const name = req.body.name;
    const logo = req.body.logo;
    const logo_name = req.body.logo_name;

    const setting = {
        name,
        logo,
        logo_name
    }
    db.query(`update setting set? where id = ${id}`, setting, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                message: '服务器错误'
            });
        } else {
            res.json({
                code: 200,
                message: '修改成功'
            });
        }
    });
});

// 修改当前设置
router.post('/set', (req, res) => {
    const id = req.body.id;

    //先将所有设置的状态改为0
    db.query(`update setting set status = 0`, (err, result) => {
        if (err) {
            return res.json({
                code: 500,
                message: '服务器错误'
            })
        }

        db.query(`update setting set status = 1 where id = ${id}`, (err, result) => {
            if (err) {
                res.json({
                    code: 500,
                    message: '服务器错误'
                })
            } else {
                res.json({
                    code: 200,
                    message: '设置成功'
                })
            }
        })
    })
})

module.exports = router;